package com.yc.ycpaimon.widget

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.yc.ycpaimon.R
import com.yc.ycpaimon.data.entity.VersionEntity
import com.yc.ycpaimon.databinding.VersionUpgradeDialogBinding
import com.yc.ycpaimon.notification.NotificationUtil

/**
 * Creator: yc
 * Date: 2022/3/11 10:57
 * UseDes:版本更新提示对话框
 */
@SuppressLint("SetTextI18n")
class VersionUpgradeDialog : Dialog {
    private val mViewBind: VersionUpgradeDialogBinding by lazy { VersionUpgradeDialogBinding.inflate(layoutInflater) }

    constructor(fragment: Fragment) : this(fragment.requireContext(), fragment)
    constructor(activity: AppCompatActivity) : this(activity, activity)
    constructor(context: Context, lifecycleOwner: LifecycleOwner) : super(context, R.style.CommonDialogStyle) {
        lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                Log.e("VersionUploadDialog", "onDestroy: ")
                if (this@VersionUpgradeDialog.isShowing) {
                    cancel()
                }
            }
        })
    }

    init {
        setContentView(mViewBind.root)
        setCancelable(true)
        setCanceledOnTouchOutside(true)
        mViewBind.tvUpgradeCancel.setOnClickListener { dismiss() }
        mViewBind.tvUpgradeContent.movementMethod = ScrollingMovementMethod.getInstance()
    }


    fun setData(data: VersionEntity): VersionUpgradeDialog {
        mViewBind.apply {
            tvUpgradeContent.text = data.upgradeContent!!
            tvApkSize.text = data.apkSize
            tvUpgradeStart.setOnClickListener {
                dismiss()
                downloadApk(data.apkUrl!!)
            }
        }
        return this
    }

    fun setCancel(call: (View) -> Unit) {
        mViewBind.tvUpgradeCancel.setOnClickListener(call)
    }

    /**
     * 下载apk
     * @param apkUrl String
     */
    private fun downloadApk(apkUrl: String) {
        Toast.makeText(context, "开始后台下载中...", Toast.LENGTH_LONG).show()


    }
}